// pages/community/edit/edit.js
var common = require('../../../utils/common.js')
var util = require('../../../utils/util.js')
var config = require('../../../config.js')
const app = getApp()

var sourceType = [['camera'], ['album'], ['camera', 'album']]
var sizeType = [['compressed'], ['original'], ['compressed', 'original']]

Page({

  /**
   * 页面的初始数据
   */
  data: {
    imageList: [],
    sourceTypeIndex: 2,
    sourceType: ['拍照', '相册', '拍照或相册'],

    sizeTypeIndex: 2,
    sizeType: ['压缩', '原图', '压缩或原图'],

    countIndex: 1,
    count: [1, 2, 3, 4, 5, 6, 7],
    title: "",
    content: "",
    discussid: "",
    upload_percent: 50,
     offline: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    const id = util.NewGuid();
    this.setData({
      discussid: id
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  // onShareAppMessage: function () {

  // },
  formSubmit: function (e) {
    //TODO 过滤内容
    const that = this;
    //发布url
    const url = "/apid/c/108";
    //帖子id
    const id = that.data.discussid;
    //获取用户的id
    e.detail.value.accountid = app.globalData.accountid;
    if (e.detail.value.title == '') {
      util.ShowMessage("标题不能为空");
      return false;
    }
    if (e.detail.value.content == '') {
      util.ShowMessage("内容不能为空");
      return false;
    }

    const lvurl = "/apid/r/146"
    util.DoCommand(lvurl, null, e.detail.value, function (passdata) {
      if (passdata.pass == 0) {
        util.DoCommand(url, "id=" + id, e.detail.value, function (data) {
          //提示发布成功
          wx.showToast({
            title: '发布成功',
            icon: 'success',
            duration: 2000
          });
          //刷新列表页数据
          var pages = getCurrentPages();
          if (pages.length > 1) {
            //上一个页面实例对象
            var prePage = pages[pages.length - 2];
            //改更列表页的状态
            prePage.getDiscussList(true);
          }
          //跳转页面
          setTimeout(function () {
            wx.switchTab({
              url: '/pages/community/communityList/communityList'
            })
          }, 2000)
        }, null, that)
      }
      else{
        util.ShowMessage("内容不能含有敏感词!")
      }
    }, null, that)

  },
  countChange: function (e) {
    this.setData({
      countIndex: e.detail.value
    })
  },
  chooseImage: function () {
    var that = this;
    var imageList = that.data.imageList;
    wx.chooseImage({
      sourceType: sourceType[this.data.sourceTypeIndex],
      sizeType: sizeType[this.data.sizeTypeIndex],
      count: this.data.count[this.data.countIndex],
      success: function (res) {
        // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
        var tempFiles = res.tempFiles
        //循环把图片加入上传列表
        for (var i in tempFiles) {
          tempFiles[i]['upload_percent'] = 0
          tempFiles[i]['path_server'] = ''
          imageList.push(tempFiles[i])
        }
        that.setData({
          imageList: imageList,
        })
        //循环把图片上传到服务器 并显示进度
        for (var j in imageList) {
          if (imageList[j]['upload_percent'] == 0) {
            upload_file_server(that, imageList, j)
          }
        }

      }
    })
  },
  previewImage: function (e) {
    var current = e.target.dataset.src
    wx.previewImage({
      current: current,
      urls: this.data.imageList
    })
  },
  isblack:function(){
   
  }
})

function upload_file_server(that, upload_picture_list, j) {
  // console.log("开始上传" + j + "图片到服务器：")
  //console.log(upload_picture_list[j])
  /***************图片上传开始***************** */
  var imgSaveUrl = "/apid/c/116";
  //调用接口上传文件
  const baseurl = app.globalData.serverBaseAddr;
  //帖子id
  const discussid = that.data.discussid;
  var url = baseurl + "/apip/discuss/imageupload";
  var params = util.GetSign(null);
  url = url + "?" + params
  var upload_task = wx.uploadFile({
    url: url,
    filePath: upload_picture_list[j]['path'],//上传的文件本地地址,
    name: 'file',
    formData: {
    },
    success: function (res2) {
      if (res2.statusCode == 200) {
        //保存图片
        const resultData = JSON.parse(res2.data)
        if (resultData.code == 0) {
          const imgid = util.NewGuid();
          const data = { "discussid": discussid, "imgurl": resultData.data };
          util.DoCommand(imgSaveUrl, "id=" + imgid, data, function (data) {
            // imageList.push(res2.data)
            upload_picture_list[j]['path_server'] = resultData.data
            that.setData({
              imageList: upload_picture_list
            })
            //  console.log("图片上传" + j + "到服务器完成：")
            //  console.log(upload_picture_list[j])
          }, null, that)
        }
        else {

        }

      }
      else {
        util.ErrorMessage();
      }

    }
  })
  // 上传进度条
  upload_task.onProgressUpdate((res) => {
    // console.log('上传进度', res.progress)
    // console.log('已经上传的数据长度', res.totalBytesSent)
    // console.log('预期需要上传的数据总长度', res.totalBytesExpectedToSend)
    upload_picture_list[j]['upload_percent'] = res.progress
    // console.log('第' + j + '个图片上传进度：' + upload_picture_list[j]['upload_percent'])
    // console.log(upload_picture_list)
    that.setData({
      upload_picture_list: upload_picture_list
    })

  })

  /***************图片上传结束***************** */
}